﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using LogCat.Utility;

namespace LogCat
{
    public partial class Config : Form
    {
        public Config()
        {
            InitializeComponent();
        }

        private void button_test_Click(object sender, EventArgs e)
        {
            TestRule();
        }

        private void button_save_Click(object sender, EventArgs e)
        {
            if(!TestRule()){
                MessageBox.Show("正则表达式错误！", "提示", MessageBoxButtons.OK);
                return;
            }

            if (sql.Text.Equals("")) {
                sql.Text = "select * from log";
            }

            ConfigInfo info = new ConfigInfo();

            info.log_raw    = log_raw.Text;
            info.log_rule   = log_rule.Text;
            info.sql_defult = sql.Text;

            ConfigUtility.save(info);

            MessageBox.Show("配置已保存，请重新加载日志！", "提示", MessageBoxButtons.OK);
            Application.Restart();
        }

        //测试正则表达式
        private bool TestRule() {

            log_data.BackColor = Color.Red;
            if (log_raw.Text.Equals("") || log_rule.Text.Equals(""))
            {
                log_data.Text = "日志内容或正则表达式为空!";
                return false;
            }

            Match mt = new Regex(log_rule.Text).Match(log_raw.Text);

            if (!mt.Success)
            {
                log_data.Text = "无法匹配内容!";
                return false;
            }

            if (mt.Groups.Count < 2)
            {
                log_data.Text = "匹配结果为空!";
                return false;
            }

            string result = "";
            for (int i = 1; i < mt.Groups.Count; i++)
            {
                result += "[field" + i + "=" + mt.Groups[i].Value + "]、";
            }

            log_data.Text = result;
            log_data.BackColor = Color.Green;
            return true;
        }

        private void Config_Load(object sender, EventArgs e)
        {
            this.log_raw.Text   = ConfigUtility.config.log_raw;
            this.log_rule.Text  = ConfigUtility.config.log_rule;
            this.sql.Text       = ConfigUtility.config.sql_defult;
        }
    }
}
